import $lodash from 'lodash'
/**
 * 路由懒加载
 * @param {*} view
 * 例：loadView('dashboard/welcome/index')
 * 作用同 路由表 component: () => import('@/views/dashboard/welcome/index')
 */
export const loadView = view => {
  return resolve => require([`@/views/${view}`], resolve)
}

// 获取权限 ids
function iterationRolesMenuIds(list = [], array = []) {
  list.forEach(item => {
    if (item.permissionId && !array.includes(item.permissionId)) array.push(item.permissionId)
    if (Array.isArray(item.children)) {
      iterationRolesMenuIds(item.children, array)
    }
  })
}

function hasPermission(permission, route) {
  if (route.meta && route.meta.permission) {
    let flag = false
    for (let i = 0, len = permission.length; i < len; i++) {
      flag = route.meta.permission.includes(permission[i])
      if (flag) {
        return true
      }
    }
    return false
  }
  return true
}

function filterAsyncRouter(routerMap, permissionList) {
  const accessedRouters = routerMap.filter(route => {
    if (hasPermission(permissionList, route)) {
      if (route.children && route.children.length) {
        route.children = filterAsyncRouter(route.children, permissionList)
      }
      return true
    }
    return false
  })
  return accessedRouters
}

const permission = {
  state: {
    menus: [],
    keepAliveComponents: []
  },
  mutations: {
    SET_MENUS: (state, menus) => {
      state.menus = menus
    },
    SET_KEEPALIVECOMPONENTS: (state, list) => {
      state.keepAliveComponents = list
    }
  },
  actions: {
    setRouters({ commit }, routeInfo = {}) {
      const { routes = [], roles = [] } = routeInfo
      const asyncRoutes = $lodash.cloneDeep(routes)
      const menuRoutes = asyncRoutes[0]?.children || []
      // 菜单id
      const menuIds = []

      // 过滤 权限菜单
      if (routes && routes.length && roles && roles.length) {
        // 获取权限菜单roleId一维数组
        iterationRolesMenuIds(roles, menuIds)
      }
      // 动态菜单
      const asyncMenuRoutes = filterAsyncRouter(menuRoutes, menuIds)
      commit('SET_MENUS', asyncMenuRoutes)
      return asyncMenuRoutes

      // 不需要菜单权限
      // commit('SET_MENUS', menuRoutes)
      // return menuRoutes
    },
    setkeepAliveComponents({ commit }, list) {
      commit('SET_KEEPALIVECOMPONENTS', list)
    }
  }
}

export default permission
